package cn.xn.hrms.api.controller;

import java.io.IOException;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.xn.hrms.domain.constants.Constant;
import cn.xn.hrms.domain.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;

/**
 * @author ysz
 */
@RestController
@Slf4j
@RequestMapping("/image")
public class ImageController {

    @Resource
    private RedisUtils redisUtils;


    /**
     * 生成验证码图片
     *
     * @param timestamp
     * @param response
     * @throws IOException
     */
    @GetMapping("/verificationCode")
    @ApiOperation("生成验证码")
    public void code(@RequestParam(value = "timestamp") String timestamp, HttpServletResponse response)
            throws IOException {
        String redisKey = Constant.VERIFICATION_CODE_KEY_PREFIX + timestamp;
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 20);
        lineCaptcha.write(response.getOutputStream());
        // 验证码有效期60s
        redisUtils.saveString(redisKey, lineCaptcha.getCode(), 60L);
        // 关闭流
        response.getOutputStream().close();
    }

}
